package com.pinda.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.pagehelper.PageInfo;
import com.pinda.auth.entity.PdAuthUser;
import com.pinda.auth.view.DriverView;
import com.pinda.commonutils.Page;
import com.pinda.feign.PdAuthFeignClient;
import com.pinda.feign.PdOrderFeignClient;
import com.pinda.vo.HistoryVo;
import com.pinda.vo.PdTaskTransportVo;
import com.pinda.commonutils.Result;
import com.pinda.commonutils.StatusCode;
import com.pinda.enums.OrderStatus;
import com.pinda.enums.TransportOrderStatus;
import com.pinda.oms.entity.PdOrder;
import com.pinda.service.*;
import com.pinda.enums.DriverJobStatus;
import com.pinda.vo.UUIDToDigits;
import com.pinda.work.DTO.DriverJobDTO;
import com.pinda.work.entity.*;
import com.pinda.work.vo.Pddriverjob_TasktransportView;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 司机作业单 前端控制器
 * </p>
 *
 * @author lc
 * @since 2023-06-14
 */
@RestController
@RequestMapping("/pd-driver-job")
public class PdDriverJobController {

    @Resource
    IPdDriverJobService iPdDriverJobService;
    @Resource
    IPdTaskTransportService iPdTaskTransportService;
    @Resource
    IPdTransportOrderTaskService iPdTransportOrderTaskService;
    @Resource
    IPdTransportOrderService iPdTransportOrderService;
    @Resource
    PdOrderFeignClient pdOrderFeignClient;
    @Resource
    PdAuthFeignClient pdAuthFeignClient;
    @Resource
    IPdTaskPickupDispatchService dispatchService;


    @PostMapping("/driverLogin")
    public Result<DriverView> login(@RequestBody PdAuthUser pdAuthUser){
        return pdAuthFeignClient.driverLogin(pdAuthUser);
    }

    /**
     * 新增司机作业单
     *
     * @param dto 司机作业单信息
     * @return 司机作业单信息
     */
    @PostMapping("")
    public DriverJobDTO save(@RequestBody DriverJobDTO dto) {
        PdDriverJob driverJob = new PdDriverJob();
        BeanUtils.copyProperties(dto, driverJob);
        iPdDriverJobService.saveDriverJob(driverJob);
        DriverJobDTO result = new DriverJobDTO();
        BeanUtils.copyProperties(driverJob, result);
        return result;
    }

    /**
     * 获取待取货列表、获取历史记录列表
     */
    @GetMapping("/save/{status}/{userId}")
    public Result<List<PdDriverJob>> getDriverJobByDriverIdAndTaskId(@PathVariable Integer status,@PathVariable String userId) {

        return iPdDriverJobService.getDriverJobByDriverIdAndTaskId(userId, status);
    }
    /**
     * 提货请求
     */
    @PutMapping("/extract")
    public Result extract(@RequestBody PdTaskTransportVo pdTaskTransportVo) {
        Result result = new Result();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String format = dateFormat.format(date);
        //校验是否有在途任务
        boolean extract = iPdDriverJobService.extract(pdTaskTransportVo.getDriverId(), DriverJobStatus.PROCESSING);
        if (extract) {
            result.setFlag(false);
            result.setCode(StatusCode.ERROR);
            result.setMessage("在途任务未结束，无法提货");
            return result;
        }
        //修改司机作业单
        PdDriverJob pdDriverJob = new PdDriverJob();
        pdDriverJob.setStatus(DriverJobStatus.PROCESSING);
        pdDriverJob.setStartHandover(pdTaskTransportVo.getName());
        pdDriverJob.setTaskTransportId(pdTaskTransportVo.getTaskTransportId());
        iPdDriverJobService.upDriverJob(pdTaskTransportVo.getDriverId(), pdDriverJob);
        //修改运输任务表
        PdTaskTransport pdTaskTransportUpdate = new PdTaskTransport();
        pdTaskTransportUpdate.setId(pdTaskTransportVo.getTaskTransportId());
        pdTaskTransportUpdate.setStatus(DriverJobStatus.PROCESSING);
        pdTaskTransportUpdate.setCargoPickUpPicture(pdTaskTransportVo.getCargoPickUpPicture());
        pdTaskTransportUpdate.setCargoPicture(pdTaskTransportVo.getCargoPicture());
        pdTaskTransportUpdate.setActualPickUpGoodsTime(format);
        pdTaskTransportUpdate.setActualDepartureTime(format);
        iPdTaskTransportService.taskTransportUpdate(pdTaskTransportUpdate);
        //查询运单编号
        ArrayList<PdTransportOrderTask> list = iPdTransportOrderTaskService.saveTransportOrderTask(pdTaskTransportVo.getTaskTransportId());
        PdOrder pdOrder = new PdOrder();
        //修改运单表和订单表
        for (PdTransportOrderTask transportOrderTask : list) {
            PdTransportOrder pdTransportOrder = iPdTransportOrderService.selectById(transportOrderTask.getTransportOrderId());
            pdTransportOrder.setStatus(TransportOrderStatus.LOADED);
            iPdTransportOrderService.TransportOrderUpdate(pdTransportOrder);
            pdOrder.setStatus(OrderStatus.IN_TRANSIT.getCode());
            pdOrderFeignClient.inTransit(pdOrder);
        }
        result.setCode(StatusCode.OK);
        result.setMessage("提货成功");
        result.setFlag(true);
        return result;
    }

    /**
     * 交付
     * @param pdTaskTransportVo
     * @return
     */
    @PutMapping("/finish")
    public Result finish(@RequestBody PdTaskTransportVo pdTaskTransportVo){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String format = dateFormat.format(date);
        PdDriverJob pdDriverJob = new PdDriverJob();
        pdDriverJob.setStatus(DriverJobStatus.COMPLETED);
        pdDriverJob.setFinishHandover(pdTaskTransportVo.getName());
        pdDriverJob.setTaskTransportId(pdTaskTransportVo.getTaskTransportId());
        iPdDriverJobService.upDriverJob(pdTaskTransportVo.getDriverId(), pdDriverJob);

        PdTaskTransport pdTaskTransportUpdate = new PdTaskTransport();
        pdTaskTransportUpdate.setId(pdTaskTransportVo.getTaskTransportId());
        pdTaskTransportUpdate.setStatus(DriverJobStatus.COMPLETED);
        pdTaskTransportUpdate.setTransportCertificate(pdTaskTransportVo.getTransportCertificate());
        pdTaskTransportUpdate.setDeliverPicture(pdTaskTransportVo.getDeliverPicture());
        pdTaskTransportUpdate.setActualArrivalTime(format);
        pdTaskTransportUpdate.setActualDeliveryTime(format);
        iPdTaskTransportService.taskTransportUpdate(pdTaskTransportUpdate);
        //查询运单编号
        ArrayList<PdTransportOrderTask> list = iPdTransportOrderTaskService.saveTransportOrderTask(pdTaskTransportVo.getTaskTransportId());
        PdOrder pdOrder = new PdOrder();
        PdTaskPickupDispatch pickupDispatch = new PdTaskPickupDispatch();
        //修改运单表和订单表
        for (PdTransportOrderTask transportOrderTask : list) {
            PdTransportOrder pdTransportOrder = iPdTransportOrderService.selectById(transportOrderTask.getTransportOrderId());
            pdTransportOrder.setStatus(TransportOrderStatus.END);
            iPdTransportOrderService.TransportOrderUpdate(pdTransportOrder);
            pdOrder.setId(pdTransportOrder.getOrderId());
            pdOrder.setStatus(OrderStatus.OUTLETS_EX_WAREHOUSE.getCode());
            pdOrderFeignClient.inTransit(pdOrder);
            PdTaskTransport pdTaskTransport = iPdTaskTransportService.selectId(transportOrderTask.getTransportTaskId());
            UUIDToDigits uuid = new UUIDToDigits();
            pickupDispatch.setId("Y"+uuid.uuidToDigits());
            pickupDispatch.setOrderId(pdTransportOrder.getOrderId());
            pickupDispatch.setTaskType(2);
            pickupDispatch.setStatus(1);
            pickupDispatch.setAgencyId(pdTaskTransport.getEndAgencyId());
            pickupDispatch.setAssignedStatus(1);
            Date dateStart = new Date(date.getTime() + 1000 * 60 * 60);
            String formatStart = dateFormat.format(dateStart);
            Date dateEnd = new Date(date.getTime() + 1000 * 60 * 60 * 24);
            String formatEnd = dateFormat.format(dateEnd);
            pickupDispatch.setEstimatedStartTime(formatStart);
            pickupDispatch.setEstimatedEndTime(formatEnd);
            pickupDispatch.setCreateTime(format);
            dispatchService.insertPickup(pickupDispatch);
        }
        Result result = new Result();
        result.setCode(StatusCode.OK);
        result.setMessage("交付成功");
        result.setFlag(true);
        return result;
    }
    /**
     * 历史记录详情
     */
    @RequestMapping("/historyOne/{taskTransportId}")
    public Result<HistoryVo> history(@PathVariable String taskTransportId){
        return this.iPdDriverJobService.selectOnePdDriverJob(taskTransportId);
    }
    /**
     * 查询司机作业单，微服务调用聚合微服务获取司机作业单数据
     * @return
     */
    @PostMapping("/lcquerydrivertaskcontroller")
    public Result<PageInfo<Pddriverjob_TasktransportView>> lcquerydrivertaskcontroller(@RequestBody Page<Pddriverjob_TasktransportView> page){
        PageInfo pageInfo = this.iPdDriverJobService.PdddriverjobTasktransportService(page);
        return new Result<>(true,StatusCode.OK,"查询成功",pageInfo);
    }
    @PostMapping("/uploadController")
    public String uploadController(@RequestBody MultipartFile myFile) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tBDtxb5zU2extkovwUW";
        String accessKeySecret = "oFZi4U5KRMtq1kZy8igFLCXcOD9l2U";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "projectvue";
        //你上传到oss后的名字 会根据日期帮你创建文件夹。
        String objectName = String.valueOf(UUID.randomUUID());
        String hz = myFile.getOriginalFilename().substring(myFile.getOriginalFilename().indexOf(".") + 1);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = myFile.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName + "." + hz, inputStream);
        } catch (Exception oe) {

        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //https://qy151.oss-cn-hangzhou.aliyuncs.com/2022/6/10/20d3d7e6b5bb455cb548675501f7270fgdnj.jpg
        String url = "https://" + bucketName + "." + endpoint + "/" + objectName + "." + hz;
        return url;
    }
}
